package com.yiqi.news.wxapi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;

import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DeviceUtils;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.yiqi.news.R;
import com.yiqi.news.app.utils.IoUtil;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.autosize.utils.LogUtils;


public class QQSdk {

    Activity mContext;
    Tencent mTencent;
    QQListener mListener;

    public QQSdk(Activity context, String appId) {
        mContext = context;
        mTencent = Tencent.createInstance(appId, context);
        LogUtils.e("==========>>>" + mTencent);
    }

    public void authorize(final OnLoginOk<QQToken> listener) {
        if (mTencent.isSessionValid()) {
            LogUtils.e("QQToken = " + mTencent.getQQToken());
            listener.onLogin(mTencent.getQQToken());
        } else {
            mListener = new QQListener() {
                @Override
                protected void doComplete(JSONObject values) {
                    initOpenidAndToken(values);
                    listener.onLogin(mTencent.getQQToken());

                }
            };
            mTencent.login(mContext, "get_simple_userinfo", mListener);
        }
    }

    public static String saveAsTemp(Context context, Bitmap bitmap) {
        FileOutputStream out = null;
        File file = new File(context.getExternalCacheDir(), "share1.jpg");
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            out = new FileOutputStream(file);
            //#2256 java.lang.IllegalStateException  Can't compress a recycled bitmap
            if (!bitmap.isRecycled()) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                bitmap.recycle();
            }
            out.flush();
            return file.toString();
        } catch (IOException e) {
            IoUtil.close(out);
//            CrashReport.postCatchedException(e);
        } catch (IllegalStateException e) {
            IoUtil.close(out);
//            CrashReport.postCatchedException(e);
        } finally {
            LogUtils.e("share " + file);
        }
        return null;
    }


    public void shareNetImage(String netImageUrl, boolean isQQ) {
        if (!DeviceUtils.isPackageExist(mContext, "com.tencent.mobileqq")) {
            ArmsUtils.makeText(mContext, "您未安装QQ!");
            return;
        }
        Observable.just(1).subscribeOn(Schedulers.newThread()).subscribe(a -> {
            Bitmap bitmap = BitmapFactory.decodeStream(new URL(netImageUrl).openStream());
            try {
                String path = saveAsTemp(mContext, bitmap);
                if (isQQ) {
                    shareImg(path);
                } else {
                    shareQzoneImg(path);
                }
            } catch (Exception e) {

            }
        });
    }


    public void shareImage(Bitmap bitmap, boolean isQQ) {
        if (!DeviceUtils.isPackageExist(mContext, "com.tencent.mobileqq")) {
            ArmsUtils.makeText(mContext, "您未安装QQ!");
            return;
        }
        String path = saveAsTemp(mContext, bitmap);

        Bundle params = new Bundle();
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, path);
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
        if (!isQQ) {
            params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
        }
        IUiListener listener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {
            }
        };
        mTencent.shareToQQ(mContext, params, listener);
    }

    public boolean checkInstalled() {
        if (!DeviceUtils.isPackageExist(mContext, "com.tencent.mobileqq")) {
            ArmsUtils.makeText(mContext, "您未安装QQ!");
            return false;
        }
        return true;
    }


    public void shareImg(String imageUrl) {
        if (!DeviceUtils.isPackageExist(mContext, "com.tencent.mobileqq")) {
            ArmsUtils.makeText(mContext, "您未安装QQ!");
            return;
        }
        Bundle params = new Bundle();
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, imageUrl);
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
        IUiListener listener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {
            }
        };
        mTencent.shareToQQ(mContext, params, listener);
    }

    public void shareQzoneImg(String imageUrl) {
        if (!DeviceUtils.isPackageExist(mContext, "com.tencent.mobileqq")) {
            ArmsUtils.makeText(mContext, "您未安装QQ!");
            return;
        }
        Bundle params = new Bundle();
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, imageUrl);
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
        IUiListener listener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {
            }
        };
        mTencent.shareToQQ(mContext, params, listener);
    }

    public void shareToQQ(String title, String desc, String photo, String url, boolean isQQ) {
        if (!DeviceUtils.isPackageExist(mContext, "com.tencent.mobileqq")) {
            ArmsUtils.makeText(mContext, "您未安装QQ!");
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        bundle.putString("summary", desc);
        if (isQQ) {
            bundle.putString("imageUrl", photo);
        } else {
            ArrayList images = new ArrayList();
            images.add(photo);
            bundle.putStringArrayList("imageUrl", images);
        }
        bundle.putString("targetUrl", url);
        bundle.putString("appName", mContext.getResources().getString(R.string.app_name));

        IUiListener listener = new IUiListener() {
            @Override
            public void onComplete(Object o) {

            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {

            }
        };

        if (isQQ) {
            mTencent.shareToQQ(mContext, bundle, listener);
        } else {
            mTencent.shareToQzone(mContext, bundle, listener);
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        Tencent.onActivityResultData(requestCode, resultCode, data, mListener);
    }


    private void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires) && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public interface OnLoginOk<T> {
        void onLogin(T info);
    }

    static class QQListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            if (null == response) {
                LogUtils.e("登录失败: 返回为空");
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                LogUtils.e("登录失败: 返回为空");
                return;
            }
            LogUtils.e("登录成功: " + response.toString());
            doComplete((JSONObject) response);
        }

        protected void doComplete(final JSONObject values) {

        }


        @Override
        public void onError(UiError e) {
            LogUtils.e("错误信息:" + e.errorDetail);
        }

        @Override
        public void onCancel() {
            LogUtils.e("取消了当前的登录操作");
        }
    }
}